package com.mantru.iotpot.modbus;


import android.content.Context;
import android.serialport.SerialPort;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SerialHelper {
    //设备ID
    public String DeviceID = "";
    //主窗体Context对象
    private Context parent;
    //串口对象
    private SerialPort com_port = null;

    public SerialHelper(String path, int baudrate){

        try {
            SerialPort serialPort = SerialPort //
                    .newBuilder(path, baudrate) // 串口地址地址，波特率
                    .parity(2) // 校验位；0:无校验位(NONE，默认)；1:奇校验位(ODD);2:偶校验位(EVEN)
                    .dataBits(7) // 数据位,默认8；可选值为5~8
                    .stopBits(2) // 停止位，默认1；1:1位停止位；2:2位停止位
                    .build();
        }
        catch (Exception ex)
        {
            Log("SerialHelper构造函数出错：" + ex.getMessage());
        }

    }






    private void Log(String value)
    {
        new Thread() {
            @Override
            public void run() {
                int error_code = 0;      //0表示没有发生异异，1表示有异常
                try
                {
                    String api_url = Common.API_Server_Url + "?txt_type=/pot/save_log/&device_id=" + DeviceID + "&code=200&timestamp=" + Common.GetTimeStamp13() + "&data=" + URLEncoder.encode(value);
                    URL url = new URL(api_url);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    InputStream is = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder builder = new StringBuilder();
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    is.close();
                    conn.disconnect();
                }
                catch(Exception ex)
                {
                    error_code = 1;
                }
            }
        }.start();
    }


}

